package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;


import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;


@RequiredArgsConstructor
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    private final IUserService userService;
    private final StringRedisTemplate stringRedisTemplate;
    private final IFollowService followService;
    private long time;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            this.creatBlod(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 返回当前笔记的相信信息
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog==null) {
            return Result.fail("笔记不存在");
        }
        //查询有关blog有关的用户
        creatBlod(blog);
        //查询blog是否点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //1.当前用户Id
        Long userId = UserHolder.getUser().getId();
        String key= BLOG_LIKED_KEY+blog.getId();
        //2.在redis中判断是否点赞
        Double success = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(success!=null);

    }

    /**
     * 用户点赞进行加减
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1.当前用户Id
        Long userId = UserHolder.getUser().getId();
        String key= BLOG_LIKED_KEY +id;
        //2.在redis中使用soutSet判断是否点赞
        Double success = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (success==null) {
            //2.2没有点赞
            //2.2.1数据库+1
            boolean isSuccessUpdate = update().setSql("liked=liked+1").eq("id", id).update();
            //2.2.2并且写入Redis,存入时间戳
            if (isSuccessUpdate) {
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //2.1已经点赞.数据库减一
            boolean isSuccessUpdate2 = update().setSql("liked=liked-1").eq("id", id).update();
            if (isSuccessUpdate2) {
                //从redis中移除
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询top5的点赞用户 zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2.解析出其中的id
        List<Long> ids = top5.stream().map(m->Long.valueOf(m)).toList();
        String idStr = StrUtil.join(",",ids);
        //3.根据用户id查询用户
        List<User> userList = userService.query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        List<UserDTO> userDTOList = BeanUtil.copyToList(userList, UserDTO.class);
        //4.返回
        return Result.ok(userDTOList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccuess = save(blog);
        if (isSuccuess ) {
            //获取到当前用户的所有粉丝id
            List<Follow> followList = followService.query().eq("follow_user_id", user.getId()).list();
            //推送所有笔记id给所有粉丝
            for (Follow follow : followList) {
                Long userId = follow.getId();
                //推送
                String key =FEED_KEY+userId;
                stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
            }
        }
        return Result.ok(user.getId());
    }

    /**
     * 实现滚动查询
     * @param max 上次查询的最小值
     * @param offset  偏移量,查询上次值中最小元素的个数
     * @return
     */
    @Override
    public Result queryBlogOffFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱  zrevrangebyscore key  max min limit offset count
        String key = FEED_KEY +userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples==null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //3.解析数据:blogId, minTime,offset
        List<Long> ids =new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os =1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //获取id
            ids.add(Long.valueOf(tuple.getValue()));
            //获取分数
            time = tuple.getScore().longValue();
            if (time == minTime) {
                os++;
            }else {
                minTime= time;
                os=1;
            }

        }
        //4.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            //查询有关blog有关的用户
            creatBlod(blog);
            //查询blog是否点过赞
            isBlogLiked(blog);
        }
        //5.封装并且返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }

    private void creatBlod(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
